<template>
  <div id="userLoginPage">
    <h1 class="title">云图图 - 登录</h1>
    <div class="desc">企业级智能协同云图库</div>
    <a-form :model="loginParam" autocomplete="off" @finish="handleSubmit">
      <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input v-model:value="loginParam.userAccount" placeholder="请输入账号" />
      </a-form-item>

      <a-form-item
        name="userPassword"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 8, message: '密码长度不能小于8位' },
        ]"
      >
        <a-input-password v-model:value="loginParam.userPassword" placeholder="请输入密码" />
      </a-form-item>

      <div class="tips">
        没有账号？
        <RouterLink to="/user/register">立即注册</RouterLink>
      </div>

      <a-form-item>
        <a-button :loading="loading" type="primary" html-type="submit" style="width: 100%">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { loginUsingPost } from '@/api/userController.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { message } from 'ant-design-vue'
import router from '@/router'

const loginParam = reactive<API.UserLoginRequest>({
  userAccount: '',
  userPassword: '',
})

const loading = ref(false)

/**
 * 登录
 */
const handleSubmit = async (values: any) => {
  loading.value = true
  try {
    const res = await loginUsingPost(values)
    /**
     * 登录成功后，将用户信息保存到本地存储中
     */
    if (res.data.code === 0 && res.data.data) {
      console.log('登录成功，返回的用户信息为：', res.data.data)
      // 登录成功请求后端获取脱敏后的用户信息，并将用户信息存储到本地
      await useLoginUserStore().fetchLoginUser()
      message.success('登录成功')
      // 登录成功后跳转到首页
      router.push({
        path: '/',
        replace: true,
      })
    } else {
      message.error('登录失败，' + res.data.message)
    }
  } catch (e) {
    message.error('登录失败，' + e)
  }
  loading.value = false
}
</script>

<style scoped>
#userLoginPage {
  max-width: 360px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 15px;
}

.desc {
  text-align: center;
  margin-bottom: 15px;
  color: #bbb;
}

.tips {
  text-align: right;
  margin-bottom: 15px;
  font-size: 12px;
  color: #bbb;
}
</style>
